package com.btpj.hospital_server.controller;

import com.btpj.hospital_server.dto.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author BTPJ  2020/8/28
 */
@Api(tags = "文件上传下载接口")
@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Value("${file.uploadLocation}")
    private String uploadLocation;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public CommonResult<String> uploadFile(@RequestParam MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.error("请选择上传文件");
        }

        String fileName = file.getOriginalFilename(); // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 文件扩展名
        String currentDateStr = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
        String uuid = UUID.randomUUID().toString();
        fileName = currentDateStr + "_" + uuid.substring(uuid.lastIndexOf("-") + 1) + suffixName; // 上传后保存的文件名
        // 注意这里必须是绝对路径
        File destFile = new File(new File(uploadLocation).getAbsolutePath() + File.separator + fileName);
        String absolutePath = destFile.getAbsolutePath();
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(destFile);
            LOGGER.info("文件上传存放地址：" + absolutePath);
        } catch (IOException e) {
            return CommonResult.error("文件上传出错" + e.getMessage());
        }
        return CommonResult.success(absolutePath.substring(absolutePath.lastIndexOf("/static") + "/static".length()), "文件上传成功");
    }
}
